import hashlib
from datetime import timedelta

from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import timezone
from django.urls import reverse

from .models import BBS_user as User
from .models import BBS_post, BBS_comments
from .forms import UserForm
from .login_forms import UserLoginForm


def index(request):
    bs = get_list_or_404(BBS_post)
    context = {'bbs_post': bs}
    return render(request, 'bbs/title.html', context=context)


def signup(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                User.objects.create(username=username, password=password)
                msg = '注册成功.'
                context = {'form': form, 'msg': msg}
                return render(request, 'bbs/msg.html', context=context)
            else:
                error_msg = '用户名已存在.'
                context={'form': form, 'error_msg': error_msg}
                return render(request, 'bbs/signup.html', context=context)
    else:
        form = UserForm()

    context = {'form': form}
    return render(request, 'bbs/signup.html', context=context)


def login(request):
    def get_sid(data):
        return hashlib.md5(data.encode()).hexdigest()

    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        #  print(form)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            if User.objects.filter(username=username, password=password):
                delta = timedelta(days=1)
                expire_time = timezone.now() + delta
                session_data = expire_time.strftime('%s')
                session_id = get_sid('%s:%s' % (username, session_data))
                request.session[session_id] = session_data
                url = reverse('bbs:index')
                r = HttpResponseRedirect(url)
                r.set_cookie('sid', session_id, int(delta.total_seconds()))
                return r
            else:
                msg = "登陆失败."
                context = {'form': form, 'msg': msg}
                return render(request, "bbs/login.html", context=context)
    else:
        form = UserLoginForm()
    context = {'form': form}
    return render(request, 'bbs/login.html', context=context)


def detail(request, bbs_id):
    bbs_post = get_object_or_404(BBS_post, pk=bbs_id)
    c = BBS_comments.objects.filter(com_post=bbs_id)
    context = {'bs_p': bbs_post, 'comm': c}
    if request.method == 'POST':
        comm = request.POST
        BBS_comments.objects.create(com_name=comm['name'], com_post=bbs_post, com_content=comm['comment'])
        c = BBS_comments.objects.filter(com_post=bbs_id)
        context['comm'] = c
        #  print('>>>>>>>>>>', context['comm'])
        return render(request, 'bbs/detail.html', context=context)
    return render(request, 'bbs/detail.html', context=context)

